<?php
/**
 * 江南长城周边景区
 */
class Jiangncc extends BZ_Controller
{
    public function _init()
    {
        $this->load->helper(array('api', 'common'));
        $this->load->model('scenery_base_model', 'scenery_base');
        $this->load->model('scan_recommend_products_model', 'scan_recommend_products');
        $this->load->model('bind_user_model', 'bind_user');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('user_model', 'user');
    }

  /**
     * 周边玩乐
     */
    public function index()
    {
        $data = array();

        $sid = $this->input->get('sid');
        $sid = $sid ? $sid : 471;

        $openUser = json_decode(get_cookie('bzopen'), TRUE);
        if (validateWeiXin()) {
            if (empty($openUser['openid'])) {
                $openUser = $this->weChat($sid);
            }
            if (! empty($openUser['openid'])) {
                $bindUser = $this->bind_user->find($openUser);
                if ($bindUser->num_rows() > 0) {
                    $user = $this->user->findById($bindUser->row()->uid);
                    if ($user->num_rows() > 0) {
                        $error = $this->_login($user->row());  //微信过来  直接登录
                        if ($error) {
                            $this->alertError($error);
                        }
                    }
                } else {
                    $this->createUser($openUser);
                }
            }
        }

        $scanRecommend = $this->scan_recommend_products->findProductsId(array('sid' =>$sid));
        $recommendProducts = array();
        if ($scanRecommend->num_rows() > 0) {
            foreach ($scanRecommend->result() as $key => $value) {
                $recommendProducts[$value->type] =  $value->products_id ? explode(',', rtrim($value->products_id, ',')) : '';
            }
        }
        $sceneryResult = '';
        if (!empty($recommendProducts[1])) {
            $sceneryResult = $this->scenery_base->sceneryHotTickets(array('sid' => $recommendProducts[1], 'not_sid' => $sid, 'limit' => 20)); //按推荐景区来
            $data['sceneryList'] = $sceneryResult->result();
        }

        if (!empty($recommendProducts[2])) {
            $apiUrl = $this->config->hotel_api_url. 'admin/OrderCenter/HotelGrid';
            $hotelResult = json_decode(apiCurl($apiUrl, array('hotel_id' => json_encode($recommendProducts[2]), 'size' => 20)));
            if ($hotelResult->status === 0) {
                $data['hotelList'] = $hotelResult->data->list;
            }
        }

        if (! empty($recommendProducts[4])) {
            $result = $this->scenery_base->sceneryHotTickets(array('sid' => $recommendProducts[4], 'not_sid' => $sid, 'limit' => 20)); //按推荐景区来
            if ($result->num_rows() > 0) {
                $data['restaurantList'] = $result->result();
            }
        }
        $this->scenery_base->sceneryHotTickets(array('sid' => ['677'], 'not_sid' => $sid, 'limit' => 20));

        $this->load->view('scenic/jiangncc/index', $data);
    }

    /**
     * 微信授权
     */
    protected function weChat()
    {
        include_once(getcwd()."/application/libraries/wxpay/WxPayPubHelper/WxPayPubHelper.php");
        $jsapi = new JsApi_pub();
        if (!isset($_GET['code'])) {
            $return_url = urlencode(site_url('scenic/jiangncc/index').'?sid='. $sid);
            $url = $jsapi->createOauthUrlForCode($return_url);
            header("Location:$url");
        }

        $jsapi->setCode($_GET['code']);
        $result = $jsapi->curl($jsapi->createOauthUrlForOpenid());
        $urlOne = "https://api.weixin.qq.com/sns/userinfo?access_token=".$result->access_token."&openid=".$result->openid."&lang=zh_CN";
        $userInfo = $jsapi->curl($urlOne);
        $openUser = array('openid' => $userInfo->openid, 'personal_photo' => $userInfo->headimgurl, 'alias_name' => filterEmoji($userInfo->nickname));
        set_cookie('bzopen', json_encode($openUser), 7200);
        return $openUser;
    }

    /**
     * 如果用户没有账号就让他注册 并登陆
     */
    private function createUser($userInfo)
    {
        $this->db->trans_begin(); //开启事务  开始插入数据
        $parentName = get_cookie('true_user');
        $parent_id = UTID_BEIZHU;
        $amount_bonus = 0;
        if (!empty($parentName)) {
            $parent = $this->user->validateName($parentName);
            if ($parent->num_rows() > 0) {
                $parent_id = $parent->row()->uid;
                if (in_array($parent_id, array(2002745, 3519856))) { //蛇蟠岛的就送游币
                    $amount_bonus = 100;
                }
            }
        }

        $postData = array(
            'user_name' => isset($userInfo['user_name']) ? $userInfo['user_name'] : '',
            'mobile_phone' => isset($userInfo['mobile_phone']) ? $userInfo['mobile_phone'] : '',
            'personal_photo' => isset($userInfo['personal_photo']) ? $userInfo['personal_photo'] : '',
            'alias_name' => isset($userInfo['alias_name']) ? $userInfo['alias_name'] : ''
        );
        $userId = $this->user->insertUser($postData, $parent_id);
        $userAccountId = $this->user_account->insertUserAccount($userId, $amount_bonus);
        if (validateWeiXin()) {
            $this->bind_user->insertBindUser(array('uid' => $userId, 'openid' =>$userInfo['openid']));
        } elseif (validateAliapp()) {
            $this->bind_user->insertBindUser(array('uid' => $userId, 'ali_user_id' =>$userInfo['ali_user_id']));
        }

        if ($this->db->trans_status() === FALSE || !$userId || !$userAccountId) {
            $this->db->trans_rollback();
             return '用户购买失败';
        } else {
            $this->db->trans_commit();
            // 注册成功了 准备登陆
            $userType = $this->usertype(UTID_CUSTOMER);
            $session = array(
                'ACT_UID'        => $userId,
                'ACT_UTID'       => UTID_CUSTOMER,
                'ACT_TYPENAME'   => urlencode($userType['type_zh']),
                'ACT_TYPE'       => $userType['type_en'],
                'ACT_EXTRA'      => 0,
                'ALIAS_NAME'     => $postData['alias_name'],
                'OWNER_ID'       => $userId,
                'OWNER_NAME'     => $postData['user_name'],
                'PARENT_ID'      => 16,
                'PERSONAL_PHOTO' => $postData['personal_photo']
            );
            set_cookie('frontUser', serialize($session), 43250);
            $this->_setLogin($session); //设置登录信息
        }
    }

    /**
     * 用户登陆
     */
    private function _login($user)
    {
        if ($user->user_type & UTID_PROVIDER) {
            return '供应商账号不可购买哦';
        }

        if ($user->flag == 2) {
            return '此帐号已被冻结，请与管理员联系';
        }
        $userType = $this->usertype($user->user_type);
        $session = array(
            'ACT_UID'        => $user->uid,
            'ACT_UTID'       => $user->user_type,
            'ACT_TYPENAME'   => urlencode($userType['type_zh']),
            'ACT_TYPE'       => $userType['type_en'],
            'ACT_EXTRA'      => $user->extra,
            'ALIAS_NAME'     => urlencode($user->alias_name),
            'OWNER_ID'       => $user->uid,
            'OWNER_NAME'     => $user->user_name,
            'PARENT_ID'      => $user->parent_id,
            'PERSONAL_PHOTO' => urlencode($user->personal_photo),
        );
        set_cookie('frontUser', serialize($session), 43250);
        $this->_setLogin($session);
        return false;
    }

    /**
     * 设置登录信息
     */
    private function _setLogin($session)
    {
        $this->uid = $session['ACT_UID']; //获取session uid
        $this->userType = $session['ACT_UTID']; //获取用户类型
        $this->userName = $session['OWNER_NAME']; //获取用户名
        $this->aliasName = urldecode($session['ALIAS_NAME']); //获取用户别名
        $this->userTypeEn = $session['ACT_TYPE']; //获取英文名
        $this->userTypeName = urldecode($session['ACT_TYPENAME']); //获取用户别名
        $this->userParentId = $session['PARENT_ID']; //获取上级用户编号
        $this->personalPhoto = '';
    }



}